﻿using Microsoft.Data.SqlClient;

namespace DatabaseProxy.DatabaseProxy;

public partial class DatabaseProxyCore
{
    public static async Task<T?> GetEntityByIdAsync<T>(int id) where T : IDatabaseTable
    {
        using SqlConnection connection = new(ConnectionString);
        await connection.OpenAsync();
        string sql = "";
        await Task.Run(() =>
        {
            sql = $"SELECT {string.Join(',', Tool<T>.Columns.Keys)} FROM {Tool<T>.TableName} WHERE {Tool<T>.PrimaryKeyName}={id}";
        });
        using SqlCommand command = new(sql, connection);
        var reader = await command.ExecuteReaderAsync();
        var result = default(T);
        if (reader.HasRows)
        {
            while (reader.Read())
            {
                foreach(var pair in Tool<T>.Columns)
                {
                    pair.Value.SetValue(result, reader[pair.Key] is DBNull ? null : reader[pair.Key]);
                }
            }
        }
        return result;
    }
}
